package sort;


import java.util.Arrays;

import static util.SwapUtil.swap;

/**
 * @BelongsProject: leetcode
 * @BelongsPackage: sort
 * @author: 肖
 * @date: 2022/1/25 17:12
 * @Description: 堆排序
 * @since JDK 11
 */

public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {2,3,4,1};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void heapSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
//        for (int i = 0; i < arr.length; i++) {
//            heapInsert(arr, i);
//        }
//        整体效率更高  或者直接让整个数组变成大根堆 （大顶堆)
        for(int i=arr.length-1;i>=0;i--){
            heapify(arr,i,arr.length);
        }
        int heapSize = arr.length;
        swap(arr, 0, --heapSize);
        while (heapSize > 0) {
            heapify(arr, 0, heapSize);
            swap(arr, 0, --heapSize);
        }
    }

    //    某个数在index 插入后看是否向上移动
    public static void heapInsert(int[] arr, int index) {
        while (arr[index] > arr[(index - 1) / 2]) {
            swap(arr, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }

    public static void heapify(int[] arr, int index, int heapSize) {
//        左孩子的下标
        int left = index * 2 + 1;
        while (left < heapSize) {
//            返回子节点中最大值的下标
            int largest = left + 1 < heapSize && arr[left] < arr[left + 1] ? left + 1 : left;
            largest = arr[largest] > arr[index] ? largest : index;
            if (largest == index) {
                break;
            }
            swap(arr, index, largest);
            index = largest;
            left = index * 2 + 1;
        }
    }

}
